﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using S3.Biz;
using S3.Common;
using S3.DataModel;

namespace S3
{
    public partial class ReportPlaying : S3FormBase
    {
        private bool _isChanged;
        public ReportPlaying()
        {
            InitializeComponent();
            InitConfig();
            LoadData();

            if (gridViewPlaying.RowCount <= 0) btnFinish.Enabled = false;
        }

        private void InitConfig()
        {
           // gridPlaying.AutoGenerateColumns = false;
        }

        private void LoadData()
        {
            using (var dailyEntryManager = new DailyTimingEntryManager())
            {
                IQueryable<DailyTimingEntry> list = dailyEntryManager.GetPlayingDesks();

                //Check
                if (list == null || list.Count() <= 0)
                {
                    btnFinish.Enabled = false;
                }

                list = list.OrderByDescending(a => a.StartTime);

                //Define
                var extendDailyEntryList = new List<ExtendDailyEntry>();
                decimal moneyTotal = 0;
                decimal totalTime = 0;
                decimal moneyService = 0;
                decimal moneyByDesk = 0;
                decimal moneyPaidHelp = 0;
                decimal moneyGame = 0;

                foreach (DailyTimingEntry item in list)
                {
                    decimal subGameMoney = 0;
                    decimal subServiceMoney = 0;
                    decimal subPaidMoney = 0;
                    decimal subTotalMoney = 0;

                    dailyEntryManager.CalTotalMoneyByDesk(item.InvoiceNo, ref subGameMoney, ref subTotalMoney);

                    var entry = new ExtendDailyEntry
                                    {
                                        TimingServiceName = item.TimingServiceName,
                                        EndTime = string.Format(Constants.Format_Date_Time, DateTime.Now),
                                        Type = item.Type,
                                        Notes = item.Notes,
                                        StartTime = string.Format(Constants.Format_Date_Time, item.StartTime),
                                        TotalMoney = Utils.StringFormatMoney(subTotalMoney),
                                        //Paid = Utils.StringFormatMoney(subPaidMoney),
                                        StaffName = item.StaffName,
                                        SessionBy =
                                            string.IsNullOrEmpty(item.SessionBy) ? "(Chưa bàn giao)" : item.SessionBy,
                                        ServiceMoney = Utils.StringFormatMoney(subServiceMoney),
                                        GameMoney = Utils.StringFormatMoney(subGameMoney)
                                    };


                    decimal totalSubTime = Convert.ToDecimal(DateTime.Now.Subtract(item.StartTime).TotalMinutes);
                    if (totalSubTime < 1)
                    {
                        totalSubTime = 1;
                    }

                    totalTime = totalTime + totalSubTime;

                    entry.TotalTime = Utils.StringFormatMoney(totalSubTime);

                    extendDailyEntryList.Add(entry);

                    //calculate sub total
                    moneyGame = moneyGame + subGameMoney;
                    moneyByDesk = moneyByDesk + subTotalMoney;
                    moneyService = moneyService + subServiceMoney;
                    moneyPaidHelp = moneyPaidHelp + subPaidMoney;
                    moneyTotal = moneyTotal + moneyByDesk + moneyPaidHelp;
                }

                //Display grid
                gridPlaying.DataSource = extendDailyEntryList;

                //Display total                
                lblTotalTime.Text = Utils.StringFormatMoney(totalTime);
                lblTotalGameMoney.Text = Utils.StringFormatMoney(moneyGame);
                lblTotalServiceMoney.Text = Utils.StringFormatMoney(moneyService);
                //lblTotalPaidHelp.Text = Utils.StringFormatMoney(moneyPaidHelp);
                lblTotalMoneyByDesk.Text = Utils.StringFormatMoney(moneyByDesk);
                //lblTotalMoney.Text = Utils.StringFormatMoney(moneyPaidHelp + moneyByDesk);
            }
        }

        private PopupProgress _popupProgress;

        public override void DoUpdateData()
        {
            try
            {
                using (var dailyEntryManager = new DailyTimingEntryManager())
                {
                    if (gridViewPlaying.SelectedRowsCount > 0)
                    {
                        foreach (int rowIndex in gridViewPlaying.GetSelectedRows())
                        {
                            dailyEntryManager.StopPlaying(gridViewPlaying.GetRowCellValue(rowIndex, "TimingServiceName").ToString(),
                                                          Convert.ToDecimal(gridViewPlaying.GetRowCellValue(rowIndex, "ServiceMoney")),
                                                          Convert.ToDecimal(gridViewPlaying.GetRowCellValue(rowIndex, "TotalMoney")),
                                                          DateTime.Now);
                        }
                    }
                    else
                    {
                        for (int rowIndex = 0; rowIndex < gridViewPlaying.RowCount; rowIndex++ )
                        {
                            dailyEntryManager.StopPlaying(gridViewPlaying.GetRowCellValue(rowIndex, "TimingServiceName").ToString(),
                                                          Convert.ToDecimal(gridViewPlaying.GetRowCellValue(rowIndex, "ServiceMoney")),
                                                          Convert.ToDecimal(gridViewPlaying.GetRowCellValue(rowIndex, "TotalMoney")),
                                                          DateTime.Now);
                        }
                    }
                }

                //Reload
                LoadData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Error: " + ex.Message);
            }

            _isChanged = true;            
        }

        private void btnFinish_Click(object sender, EventArgs e)
        {
            if (
                XtraMessageBox.Show("Bạn chắc chắn muốn thanh toán các máy được chọn dưới đây?", "Chú ý",
                                MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                _popupProgress = new PopupProgress { FormOwner = this, Action = UserAction.Update};
                _popupProgress.ShowDialog();                
            }
        }


        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                gridViewPlaying.SelectAll();
            }
            else
            {
                if (gridViewPlaying.SelectedRowsCount > 0)
                {
                    gridViewPlaying.ClearSelection();
                }
            }
        }

        private void ReportPlaying_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

        #region ProcessCmdKey

        /// <summary>
        /// Close form if click ESC
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                if (msg.WParam.ToInt32() == (int) Keys.Escape)
                {
                    Close();
                }
                else
                {
                    return base.ProcessCmdKey(ref msg, keyData);
                }
            }
            catch (Exception Ex)
            {
                XtraMessageBox.Show("Key Overrided Events Error:" + Ex.Message);
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        #endregion
    }
}